<template>
  <div class="admin-dashboard">
    <el-container>
      <!-- 侧边栏 -->
      <el-aside width="250px" class="sidebar">
        <div class="logo">
          <h2>智能OJ系统</h2>
          <p>管理员端</p>
        </div>

        <el-menu
          :default-active="activeMenu"
          router
          class="sidebar-menu"
          background-color="#001529"
          text-color="#fff"
          active-text-color="#1890ff"
        >
          <el-menu-item index="dashboard">
            <el-icon><DataBoard /></el-icon>
            <span>仪表盘</span>
          </el-menu-item>

          <el-menu-item index="users">
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </el-menu-item>

          <el-menu-item index="courses">
            <el-icon><Reading /></el-icon>
            <span>课程管理</span>
          </el-menu-item>

          <el-menu-item index="problems">
            <el-icon><Document /></el-icon>
            <span>题目管理</span>
          </el-menu-item>

          <el-menu-item index="submissions">
            <el-icon><Monitor /></el-icon>
            <span>提交管理</span>
          </el-menu-item>

          <el-menu-item index="settings">
            <el-icon><Setting /></el-icon>
            <span>系统设置</span>
          </el-menu-item>

          <el-menu-item index="logs">
            <el-icon><Clock /></el-icon>
            <span>系统日志</span>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 主内容区 -->
      <el-container>
        <!-- 顶部导航 -->
        <el-header class="header">
          <div class="header-left">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item>首页</el-breadcrumb-item>
              <el-breadcrumb-item>{{ getCurrentPageTitle() }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>

          <div class="header-right">
            <el-alert
              v-if="authStore.getIsTestMode()"
              title="测试模式"
              type="warning"
              description="当前处于测试模式"
              show-icon
              :closable="false"
              class="test-mode-alert"
            />
            <el-dropdown>
              <span class="user-info">
                <el-avatar
                  :size="32"
                  src="https://api.dicebear.com/7.x/avataaars/svg?seed=admin"
                />
                <span>管理员</span>
                <el-icon><ArrowDown /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>

        <!-- 内容区 -->
        <el-main class="main-content">
          <!-- 仪表盘内容 -->
          <div v-if="activeMenu === 'dashboard'" class="dashboard-content">
            <!-- 欢迎信息 -->
            <div class="welcome-section">
              <h1 class="welcome-title">系统管理控制台</h1>
              <p class="welcome-subtitle">管理用户、课程和系统设置</p>
            </div>

            <!-- 统计卡片 -->
            <div class="stats-grid">
              <div class="stat-card" v-for="stat in stats" :key="stat.key">
                <div class="stat-content">
                  <div class="stat-info">
                    <p class="stat-label">{{ stat.label }}</p>
                    <h3 class="stat-value">{{ stat.value }}</h3>
                    <p class="stat-trend" :class="stat.trendClass">
                      <el-icon><component :is="stat.trendIcon" /></el-icon>
                      {{ stat.trend }}
                    </p>
                  </div>
                  <div class="stat-icon" :class="stat.iconClass">
                    <el-icon><component :is="stat.icon" /></el-icon>
                  </div>
                </div>
              </div>
            </div>

            <!-- 快速操作 -->
            <div class="quick-actions">
              <h3 class="section-title">快速操作</h3>
              <div class="actions-grid">
                <el-card 
                  v-for="action in quickActions" 
                  :key="action.key"
                  class="action-card"
                  @click="handleQuickAction(action.key)"
                >
                  <div class="action-content">
                    <el-icon class="action-icon" :class="action.iconClass">
                      <component :is="action.icon" />
                    </el-icon>
                    <div class="action-info">
                      <h4>{{ action.title }}</h4>
                      <p>{{ action.description }}</p>
                    </div>
                  </div>
                </el-card>
              </div>
            </div>

            <!-- 最近活动 -->
            <div class="recent-activities">
              <h3 class="section-title">最近活动</h3>
              <el-card>
                <el-timeline>
                  <el-timeline-item
                    v-for="activity in recentActivities"
                    :key="activity.id"
                    :timestamp="activity.time"
                    :type="activity.type"
                  >
                    {{ activity.content }}
                  </el-timeline-item>
                </el-timeline>
              </el-card>
            </div>
          </div>

          <!-- 用户管理内容 -->
          <div v-else-if="activeMenu === 'users'" class="users-content">
            <div class="content-header">
              <h2>用户管理</h2>
              <el-button type="primary" @click="openAddUserModal">
                <el-icon><Plus /></el-icon>
                添加用户
              </el-button>
            </div>

            <el-card>
              <div class="table-header">
                <el-input
                  v-model="userSearchQuery"
                  placeholder="搜索用户..."
                  prefix-icon="Search"
                  style="width: 300px"
                />
                <div class="filter-controls">
                  <el-select v-model="userRoleFilter" placeholder="所有角色">
                    <el-option label="所有角色" value="" />
                    <el-option label="学生" value="student" />
                    <el-option label="教师" value="teacher" />
                    <el-option label="管理员" value="admin" />
                  </el-select>
                  <el-select v-model="userStatusFilter" placeholder="所有状态">
                    <el-option label="所有状态" value="" />
                    <el-option label="已激活" value="active" />
                    <el-option label="未激活" value="inactive" />
                  </el-select>
                </div>
              </div>

              <el-table :data="filteredUsers" style="width: 100%">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column label="用户信息" min-width="200">
                  <template #default="{ row }">
                    <div class="user-info">
                      <el-avatar :size="32" :src="`https://picsum.photos/seed/${row.id}/40/40`" />
                      <div class="user-details">
                        <div class="user-name">{{ row.name }}</div>
                        <div class="user-email">{{ row.email }}</div>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="角色" width="120">
                  <template #default="{ row }">
                    <el-tag :type="getRoleTagType(row.role)" size="small">
                      {{ getRoleText(row.role) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="状态" width="120">
                  <template #default="{ row }">
                    <el-tag :type="row.status === 'active' ? 'success' : 'info'" size="small">
                      {{ row.status === 'active' ? '已激活' : '未激活' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="created_at" label="注册时间" width="150">
                  <template #default="{ row }">
                    {{ formatDate(row.created_at) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                  <template #default="{ row }">
                    <el-button type="primary" size="small" @click="editUser(row)">编辑</el-button>
                    <el-button type="warning" size="small" @click="resetPassword(row.id)">重置密码</el-button>
                    <el-button 
                      v-if="row.role !== 'admin'"
                      type="danger" 
                      size="small" 
                      @click="changeUserStatus(row.id, row.status === 'active' ? 'banned' : 'active')"
                    >
                      {{ row.status === 'active' ? '禁用' : '启用' }}
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>

          <!-- 课程管理内容 -->
          <div v-else-if="activeMenu === 'courses'" class="courses-content">
            <div class="content-header">
              <h2>课程管理</h2>
              <el-button type="primary" @click="openAddCourseModal">
                <el-icon><Plus /></el-icon>
                添加课程
              </el-button>
            </div>

            <el-card>
              <div class="table-header">
                <el-input
                  v-model="courseSearchQuery"
                  placeholder="搜索课程..."
                  prefix-icon="Search"
                  style="width: 300px"
                />
                <el-select v-model="courseTeacherFilter" placeholder="所有教师">
                  <el-option label="所有教师" value="" />
                  <el-option v-for="teacher in teachers" :key="teacher.id" :label="teacher.name" :value="teacher.id" />
                </el-select>
              </div>

              <el-table :data="filteredCourses" style="width: 100%">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column label="课程名称" min-width="200">
                  <template #default="{ row }">
                    <div class="course-info">
                      <div class="course-name">{{ row.name }}</div>
                      <div class="course-code">课程代码: {{ row.code }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="teacher_name" label="授课教师" width="120" />
                <el-table-column prop="student_count" label="学生数量" width="100" />
                <el-table-column prop="assignment_count" label="作业数量" width="100" />
                <el-table-column prop="created_at" label="创建时间" width="150">
                  <template #default="{ row }">
                    {{ formatDate(row.created_at) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                  <template #default="{ row }">
                    <el-button type="primary" size="small" @click="viewCourseDetails(row)">查看</el-button>
                    <el-button type="warning" size="small" @click="editCourse(row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="deleteCourse(row.id)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>

          <!-- 其他菜单内容占位 -->
          <div v-else class="placeholder-content">
            <el-empty description="功能开发中..." />
          </div>
        </el-main>
      </el-container>
    </el-container>

    <!-- 添加用户模态框 -->
    <el-dialog v-model="addUserModalVisible" title="添加用户" width="500px">
      <el-form :model="newUser" :rules="userRules" ref="addUserFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="newUser.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="newUser.email" type="email" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="newUser.role" placeholder="请选择角色">
            <el-option label="学生" value="student" />
            <el-option label="教师" value="teacher" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门/班级">
          <el-input v-model="newUser.department" placeholder="例如：计算机学院 或 计算机1班" />
        </el-form-item>
        <el-form-item label="初始密码" prop="password">
          <el-input v-model="newUser.password" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addUserModalVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddUser">创建用户</el-button>
      </template>
    </el-dialog>

    <!-- 添加课程模态框 -->
    <el-dialog v-model="addCourseModalVisible" title="添加课程" width="500px">
      <el-form :model="newCourse" :rules="courseRules" ref="addCourseFormRef" label-width="100px">
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="newCourse.name" />
        </el-form-item>
        <el-form-item label="课程代码" prop="code">
          <el-input v-model="newCourse.code" placeholder="例如：CS101" />
        </el-form-item>
        <el-form-item label="授课教师" prop="teacher_id">
          <el-select v-model="newCourse.teacher_id" placeholder="请选择教师">
            <el-option v-for="teacher in teachers" :key="teacher.id" :label="teacher.name" :value="teacher.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程描述">
          <el-input v-model="newCourse.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="课程状态">
          <el-select v-model="newCourse.status">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addCourseModalVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddCourse">创建课程</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, Setting, Clock, Plus, Delete, Search, ArrowDown,
  UserFilled, Monitor, TrendCharts, Check, Collection, Document,
  DataBoard, Reading
} from '@element-plus/icons-vue'

const router = useRouter()
const authStore = useAuthStore()

// 当前激活的菜单
const activeMenu = ref('dashboard')

// 统计数据
const stats = computed(() => [
  {
    key: 'total-users',
    label: '总用户数',
    value: '1,234',
    trend: '较上月 +12%',
    trendClass: 'trend-up',
    trendIcon: 'TrendCharts',
    icon: 'User',
    iconClass: 'icon-primary'
  },
  {
    key: 'teachers',
    label: '教师用户',
    value: '45',
    trend: '新增 3 人',
    trendClass: 'trend-up',
    trendIcon: 'TrendCharts',
    icon: 'UserFilled',
    iconClass: 'icon-indigo'
  },
  {
    key: 'students',
    label: '学生用户',
    value: '1,189',
    trend: '新增 52 人',
    trendClass: 'trend-up',
    trendIcon: 'TrendCharts',
    icon: 'User',
    iconClass: 'icon-blue'
  },
  {
    key: 'courses',
    label: '课程总数',
    value: '28',
    trend: '新增 5 门',
    trendClass: 'trend-up',
    trendIcon: 'TrendCharts',
    icon: 'Book',
    iconClass: 'icon-green'
  },
  {
    key: 'assignments',
    label: '作业总数',
    value: '156',
    trend: '新增 12 个',
    trendClass: 'trend-up',
    trendIcon: 'TrendCharts',
    icon: 'Document',
    iconClass: 'icon-amber'
  },
  {
    key: 'submissions',
    label: '提交总数',
    value: '3,456',
    trend: '较上月 +32%',
    trendClass: 'trend-up',
    trendIcon: 'TrendCharts',
    icon: 'Monitor',
    iconClass: 'icon-red'
  }
])

// 快速操作
const quickActions = ref([
  {
    key: 'add-user',
    title: '添加用户',
    description: '创建新的用户账号',
    icon: 'User',
    iconClass: 'icon-primary'
  },
  {
    key: 'add-course',
    title: '添加课程',
    description: '创建新的课程',
    icon: 'Reading',
    iconClass: 'icon-green'
  },
  {
    key: 'add-problem',
    title: '添加题目',
    description: '创建新的编程题目',
    icon: 'Document',
    iconClass: 'icon-blue'
  },
  {
    key: 'view-logs',
    title: '查看日志',
    description: '查看系统活动日志',
    icon: 'Clock',
    iconClass: 'icon-amber'
  }
])

// 最近活动
const recentActivities = ref([
  {
    id: 1,
    content: '新用户 "张三" 注册成功',
    time: '2024-01-21 10:30:00',
    type: 'success'
  },
  {
    id: 2,
    content: '用户 "李四" 提交了作业 "算法基础"',
    time: '2024-01-21 10:25:00',
    type: 'info'
  },
  {
    id: 3,
    content: '题目 "排序算法" 被修改',
    time: '2024-01-21 10:20:00',
    type: 'warning'
  },
  {
    id: 4,
    content: '作业 "数据结构" 评测完成',
    time: '2024-01-21 10:15:00',
    type: 'success'
  }
])

// 用户管理
const users = ref([
  { id: 1, name: '张三', email: 'zhangsan@example.com', role: 'student', status: 'active', created_at: '2024-01-15' },
  { id: 2, name: '李四', email: 'lisi@example.com', role: 'teacher', status: 'active', created_at: '2024-01-10' },
  { id: 3, name: '王五', email: 'wangwu@example.com', role: 'admin', status: 'active', created_at: '2024-01-01' },
  { id: 4, name: '赵六', email: 'zhaoliu@example.com', role: 'student', status: 'inactive', created_at: '2024-01-20' }
])

const userSearchQuery = ref('')
const userRoleFilter = ref('')
const userStatusFilter = ref('')
const filteredUsers = computed(() => {
  return users.value.filter(user => {
    const matchesSearch = !userSearchQuery.value || 
      user.name.includes(userSearchQuery.value) || 
      user.email.includes(userSearchQuery.value) ||
      user.id.toString().includes(userSearchQuery.value)
    const matchesRole = !userRoleFilter.value || user.role === userRoleFilter.value
    const matchesStatus = !userStatusFilter.value || user.status === userStatusFilter.value
    return matchesSearch && matchesRole && matchesStatus
  })
})

const totalUsers = computed(() => filteredUsers.value.length)
const pagination = reactive({
  current: 1,
  size: 10,
  get start() { return (this.current - 1) * this.size + 1 },
  get end() { return Math.min(this.current * this.size, totalUsers.value) }
})

// 课程管理
const courses = ref([
  { id: 1, name: '数据结构', code: 'CS101', teacher_name: '李四', student_count: 45, assignment_count: 8, created_at: '2024-01-15' },
  { id: 2, name: '算法设计', code: 'CS102', teacher_name: '王五', student_count: 38, assignment_count: 12, created_at: '2024-01-10' },
  { id: 3, name: '计算机网络', code: 'CS103', teacher_name: '赵六', student_count: 52, assignment_count: 6, created_at: '2024-01-05' },
  { id: 4, name: '操作系统', code: 'CS104', teacher_name: '李四', student_count: 41, assignment_count: 10, created_at: '2024-01-12' }
])

const courseSearchQuery = ref('')
const courseTeacherFilter = ref('')
const filteredCourses = computed(() => {
  return courses.value.filter(course => {
    const matchesSearch = !courseSearchQuery.value || 
      course.name.includes(courseSearchQuery.value) || 
      course.code.includes(courseSearchQuery.value)
    const matchesTeacher = !courseTeacherFilter.value || course.teacher_name === courseTeacherFilter.value
    return matchesSearch && matchesTeacher
  })
})

const totalCourses = computed(() => filteredCourses.value.length)
const coursePagination = reactive({
  current: 1,
  size: 10,
  get start() { return (this.current - 1) * this.size + 1 },
  get end() { return Math.min(this.current * this.size, totalCourses.value) }
})

// 教师列表
const teachers = ref([
  { id: 1, name: '李四' },
  { id: 2, name: '王五' },
  { id: 3, name: '赵六' }
])

// 系统设置
const basicSettings = ref({
  systemName: 'CodeJudge',
  systemDescription: '在线编程评测系统，支持多语言代码提交和自动评测',
  allowRegistration: true,
  registrationApproval: false
})

const judgeSettings = ref({
  maxRunTime: 1000,
  maxMemory: 64,
  supportedLanguages: ['python', 'cpp', 'java']
})

// 系统日志
const logs = ref([
  { id: 1, type: 'success', message: '新用户 "张三" 注册成功', user: '系统', created_at: '2024-01-21 10:30:00' },
  { id: 2, type: 'info', message: '用户 "李四" 提交了作业 "算法基础"', user: '李四', created_at: '2024-01-21 10:25:00' },
  { id: 3, type: 'warning', message: '题目 "排序算法" 被修改', user: '王五', created_at: '2024-01-21 10:20:00' },
  { id: 4, type: 'success', message: '作业 "数据结构" 评测完成', user: '系统', created_at: '2024-01-21 10:15:00' },
  { id: 5, type: 'error', message: '数据库连接超时', user: '系统', created_at: '2024-01-21 10:10:00' }
])

const logTypeFilter = ref('')
const filteredLogs = computed(() => {
  return logs.value.filter(log => {
    return !logTypeFilter.value || log.type === logTypeFilter.value
  })
})

const totalLogs = computed(() => filteredLogs.value.length)
const logPagination = reactive({
  current: 1,
  size: 5,
  get start() { return (this.current - 1) * this.size + 1 },
  get end() { return Math.min(this.current * this.size, totalLogs.value) }
})

// 模态框状态
const addUserModalVisible = ref(false)
const addCourseModalVisible = ref(false)

// 新用户表单
const newUser = ref({
  username: '',
  email: '',
  role: '',
  department: '',
  password: ''
})

// 新课程表单
const newCourse = ref({
  name: '',
  code: '',
  teacher_id: '',
  description: '',
  status: 'active'
})

// 表单验证规则
const userRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const courseRules = {
  name: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入课程代码', trigger: 'blur' }],
  teacher_id: [{ required: true, message: '请选择授课教师', trigger: 'change' }]
}

// 方法定义
const getCurrentPageTitle = () => {
  const routeMap: Record<string, string> = {
    'dashboard': '仪表盘',
    'users': '用户管理',
    'courses': '课程管理',
    'problems': '题目管理',
    'submissions': '提交管理',
    'settings': '系统设置',
    'logs': '系统日志'
  }
  return routeMap[activeMenu.value] || '未知页面'
}

const logout = () => {
  authStore.logout()
  router.push('/login')
}

const handleQuickAction = (actionKey: string) => {
  switch (actionKey) {
    case 'add-user':
      openAddUserModal()
      break
    case 'add-course':
      openAddCourseModal()
      break
    case 'add-problem':
      activeMenu.value = 'problems'
      break
    case 'view-logs':
      activeMenu.value = 'logs'
      break
    default:
      ElMessage.info('功能开发中...')
  }
}

const filterUsers = () => {
  // 过滤逻辑已在computed中实现
}

const filterCourses = () => {
  // 过滤逻辑已在computed中实现
}

const filterLogs = () => {
  // 过滤逻辑已在computed中实现
}

const getRoleTagType = (role: string) => {
  switch (role) {
    case 'admin': return 'danger'
    case 'teacher': return 'warning'
    case 'student': return 'success'
    default: return 'info'
  }
}

const getRoleText = (role: string) => {
  switch (role) {
    case 'admin': return '管理员'
    case 'teacher': return '教师'
    case 'student': return '学生'
    default: return '未知'
  }
}

const formatDate = (date: string) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

const getLogIcon = (type: string) => {
  switch (type) {
    case 'success': return 'Check'
    case 'info': return 'InfoFilled'
    case 'warning': return 'Warning'
    case 'error': return 'CircleClose'
    default: return 'InfoFilled'
  }
}

const getLogIconClass = (type: string) => {
  return `log-icon-${type}`
}

// 用户操作
const openAddUserModal = () => {
  addUserModalVisible.value = true
}

const editUser = (user: any) => {
  ElMessage.info(`编辑用户: ${user.name}`)
}

const resetPassword = (userId: number) => {
  ElMessageBox.confirm('确定要重置此用户的密码吗？', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('密码重置成功')
  })
}

const changeUserStatus = (userId: number, status: string) => {
  const actionText = status === 'banned' ? '禁用' : '启用'
  ElMessageBox.confirm(`确定要${actionText}此用户吗？`, '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success(`用户已${actionText}`)
  })
}

// 课程操作
const openAddCourseModal = () => {
  addCourseModalVisible.value = true
}

const viewCourseDetails = (course: any) => {
  ElMessage.info(`查看课程: ${course.name}`)
}

const editCourse = (course: any) => {
  ElMessage.info(`编辑课程: ${course.name}`)
}

const deleteCourse = (courseId: number) => {
  ElMessageBox.confirm('确定要删除此课程吗？此操作不可恢复！', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('课程已删除')
  })
}

// 系统设置
const saveBasicSettings = () => {
  ElMessage.success('系统基本设置保存成功')
}

const saveJudgeSettings = () => {
  ElMessage.success('评测设置保存成功')
}

// 系统日志
const clearSystemLogs = () => {
  ElMessageBox.confirm('确定要清空所有系统日志吗？此操作不可恢复！', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('系统日志已清空')
  })
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
}

const handleCurrentChange = (page: number) => {
  pagination.current = page
}

const handleCourseSizeChange = (size: number) => {
  coursePagination.size = size
  coursePagination.current = 1
}

const handleCourseCurrentChange = (page: number) => {
  coursePagination.current = page
}

const handleLogSizeChange = (size: number) => {
  logPagination.size = size
  logPagination.current = 1
}

const handleLogCurrentChange = (page: number) => {
  logPagination.current = page
}

// 表单提交
const submitAddUser = () => {
  ElMessage.success('用户添加成功')
  addUserModalVisible.value = false
  // 重置表单
  newUser.value = {
    username: '',
    email: '',
    role: '',
    department: '',
    password: ''
  }
}

const submitAddCourse = () => {
  ElMessage.success('课程添加成功')
  addCourseModalVisible.value = false
  // 重置表单
  newCourse.value = {
    name: '',
    code: '',
    teacher_id: '',
    description: '',
    status: 'active'
  }
}

onMounted(() => {
  // 初始化数据
  console.log('Admin页面已加载')
})
</script>

<style scoped lang="scss">
.admin-dashboard {
  height: 100vh;

  .sidebar {
    background-color: #001529;
    color: #fff;

    .logo {
      padding: 20px;
      text-align: center;
      border-bottom: 1px solid #1f1f1f;

      h2 {
        margin: 0;
        color: #1890ff;
        font-size: 18px;
      }

      p {
        margin: 5px 0 0 0;
        color: #8c8c8c;
        font-size: 12px;
      }
    }

    .sidebar-menu {
      border: none;

      .el-menu-item {
        height: 50px;
        line-height: 50px;

        &:hover {
          background-color: #1890ff !important;
        }

        &.is-active {
          background-color: #1890ff !important;
          color: #fff !important;

          .el-icon {
            color: #fff !important;
          }

          span {
            color: #fff !important;
          }
        }

        .el-icon {
          color: #fff;
          margin-right: 8px;
        }

        span {
          color: #fff;
        }
      }
    }
  }

  .header {
    background-color: #fff;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;

    .header-left {
      .el-breadcrumb {
        font-size: 14px;
      }
    }

    .header-right {
      display: flex;
      align-items: center;
      gap: 1rem;

      .test-mode-alert {
        margin: 0;
        padding: 4px 8px;
        font-size: 12px;
      }

      .user-info {
        display: flex;
        align-items: center;
        cursor: pointer;

        span {
          margin: 0 8px;
          color: #333;
        }
      }
    }
  }

  .main-content {
    background-color: #f5f5f5;
    padding: 20px;
    overflow-y: auto;
  }
}

/* 仪表盘内容 */
.dashboard-content {
  max-width: 1200px;
  margin: 0 auto;

  .welcome-section {
    margin-bottom: 2rem;
    text-align: center;

    .welcome-title {
      font-size: 2rem;
      font-weight: bold;
      color: #1f2937;
      margin-bottom: 0.5rem;
    }

    .welcome-subtitle {
      color: #6b7280;
      font-size: 1.125rem;
    }
  }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 1.5rem;
    margin-bottom: 2rem;
  }

  .stat-card {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    }

    .stat-content {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
    }

    .stat-info {
      flex: 1;

      .stat-label {
        color: #6b7280;
        font-size: 0.875rem;
        margin-bottom: 0.5rem;
      }

      .stat-value {
        font-size: 1.75rem;
        font-weight: bold;
        color: #1f2937;
        margin-bottom: 0.5rem;
      }

      .stat-trend {
        font-size: 0.875rem;
        display: flex;
        align-items: center;
        gap: 0.25rem;
        margin: 0;

        &.trend-up {
          color: #10b981;
        }

        &.trend-down {
          color: #ef4444;
        }
      }
    }

    .stat-icon {
      width: 3rem;
      height: 3rem;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 1.25rem;
      color: white;

      &.icon-primary { background: #6366F1; }
      &.icon-indigo { background: #6366F1; }
      &.icon-blue { background: #3b82f6; }
      &.icon-green { background: #10b981; }
      &.icon-amber { background: #f59e0b; }
      &.icon-red { background: #ef4444; }
    }
  }

  .section-title {
    font-size: 1.25rem;
    font-weight: bold;
    color: #1f2937;
    margin-bottom: 1rem;
  }

  .quick-actions {
    margin-bottom: 2rem;

    .actions-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
      gap: 1rem;
    }

    .action-card {
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
      }

      .action-content {
        display: flex;
        align-items: center;
        gap: 1rem;

        .action-icon {
          width: 3rem;
          height: 3rem;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 1.25rem;
          color: white;

          &.icon-primary { background: #6366F1; }
          &.icon-green { background: #10b981; }
          &.icon-blue { background: #3b82f6; }
          &.icon-amber { background: #f59e0b; }
        }

        .action-info {
          flex: 1;

          h4 {
            margin: 0 0 0.25rem 0;
            color: #1f2937;
            font-size: 1rem;
          }

          p {
            margin: 0;
            color: #6b7280;
            font-size: 0.875rem;
          }
        }
      }
    }
  }

  .recent-activities {
    .el-card {
      border-radius: 12px;
    }
  }
}

/* 用户和课程管理内容 */
.users-content,
.courses-content {
  max-width: 1200px;
  margin: 0 auto;

  .content-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.5rem;

    h2 {
      margin: 0;
      font-size: 1.5rem;
      font-weight: bold;
      color: #1f2937;
    }
  }

  .el-card {
    border-radius: 12px;
  }

  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
    padding: 1rem;
    background: #f9fafb;
    border-radius: 8px;

    .filter-controls {
      display: flex;
      gap: 1rem;
      align-items: center;
    }
  }

  .user-info,
  .course-info {
    display: flex;
    align-items: center;
    gap: 0.75rem;

    .user-details,
    .course-details {
      display: flex;
      flex-direction: column;

      .user-name,
      .course-name {
        font-weight: 500;
        color: #1f2937;
      }

      .user-email,
      .course-code {
        font-size: 0.875rem;
        color: #6b7280;
      }
    }
  }
}

/* 占位内容 */
.placeholder-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .admin-dashboard {
    .header {
      .header-right {
        flex-direction: column;
        gap: 0.5rem;
        align-items: flex-end;
      }
    }
  }

  .dashboard-content {
    .stats-grid {
      grid-template-columns: 1fr;
    }

    .actions-grid {
      grid-template-columns: 1fr;
    }
  }

  .users-content,
  .courses-content {
    .content-header {
      flex-direction: column;
      gap: 1rem;
      align-items: flex-start;
    }

    .table-header {
      flex-direction: column;
      gap: 1rem;
      align-items: flex-start;
    }
  }
}
</style>